package com.xiaoq.sites.endpoint;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.xiaoq.coms.GenericDataResponse;
import com.xiaoq.coms.GenericResponse;
import com.xiaoq.coms.util.IdGenerator;
import com.xiaoq.qiniu.QiNiuSpaceEnum;
import com.xiaoq.qiniu.UploadUtil;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;

@Api(tags={"七牛云上传接口"})
@RestController
@RequestMapping("/api/v1/upload")
public class QiNiuUploadEndpoint {
	
	
	private static final Logger LOG = LoggerFactory.getLogger(QiNiuUploadEndpoint.class);
	
	@ApiOperation(value = "添加一个图片返回URl", notes = "添加一个图片返回URl")
	@ApiResponses({ @ApiResponse(code = 200, response = GenericDataResponse.class, message = "添加一个图片返回URl") })
	@PostMapping(value = "", produces = { MediaType.APPLICATION_JSON_UTF8_VALUE })
	public ResponseEntity<?> upload(@RequestParam @ApiParam(value = "上传的图片") MultipartFile file){
		String postUrl = null;

		try {
			postUrl = UploadUtil.easyUploadByte(file, QiNiuSpaceEnum.XIAOQ_SITES.getName().toLowerCase(),
					QiNiuSpaceEnum.XIAOQ_SITES.getDomain());
			LOG.info("图片七牛云上的URL地址：" + postUrl);
			return GenericDataResponse.okWithData(postUrl);
		} catch (Exception e) {
			LOG.error(e.getMessage(), e);
			return GenericResponse.ng("海报图片发送失败,请重新发送！");
		}

	}
	
	@ApiOperation(value = "生成一个html静态页面返回URl", notes = "生成一个html静态页面返回URl")
	@ApiResponses({ @ApiResponse(code = 200, response = GenericDataResponse.class, message = "添加一个图片返回URl") })
	@PostMapping(value = "/upload1", produces = { MediaType.APPLICATION_JSON_UTF8_VALUE })
	public ResponseEntity<?> upload1(@RequestParam(value="file",required=true) @ApiParam(value = "上传的图片") String file){
		String postUrl = null;

		try {
			postUrl = UploadUtil.stringUploadByte(file, QiNiuSpaceEnum.XIAOQ_SITES.getName().toLowerCase(),
					QiNiuSpaceEnum.XIAOQ_SITES.getDomain());
			LOG.info("图片七牛云生成一个html静态页面的URL地址：" + postUrl);
			return GenericDataResponse.okWithData(postUrl);
		} catch (Exception e) {
			LOG.error(e.getMessage(), e);
			return GenericResponse.ng("生成一个html静态页面失败,请重新发送！");
		}

	}
	
	
	
	
	@ApiOperation(value = "将amr模型转成MP3", notes = "将amr模型转成MP3")
	@ApiResponses({ @ApiResponse(code = 200, response = GenericDataResponse.class, message = "将amr模型转成MP3") })
	@PostMapping(value = "/amr", produces = { MediaType.APPLICATION_JSON_UTF8_VALUE })
	public ResponseEntity<?> amr2Mp3(@RequestParam(value="audioUrl",required=true) @ApiParam(value = "amr地址") String audioUrl){
		LOG.info("amr地址"+audioUrl);
		String audoUrl = getAudioUrl(audioUrl);
		LOG.info("mp3地址"+audoUrl);
		return GenericDataResponse.okWithData(audoUrl);

	}
	
	private String getAudioUrl(String audioUrl){
		String audoUrl = null;
		try {
			String suffnix = null; // 网上下载问价的后缀名
			URL ul = new URL(audioUrl);
			HttpURLConnection conn = (HttpURLConnection) ul.openConnection();
			String contentType = conn.getContentType();
			LOG.info("contentType格式为"+contentType);
			String[]ss = contentType.split("/");
			suffnix = ss[1];
			BufferedInputStream bi = new BufferedInputStream(conn.getInputStream());
			String appDir = ResourceUtils.getURL("classpath:").getPath();
			String fileName = new IdGenerator().nextId()+"."+suffnix;
			String fileUrl = appDir+"/"+fileName;
			LOG.info("存储地址"+fileUrl);
			File file = new File(appDir,fileName);
			if(!file.exists()){
				file.getParentFile().mkdirs();
				file.createNewFile();
			}
			FileOutputStream bs = new FileOutputStream(file);
//			FileOutputStream bs = new FileOutputStream(fileUrl);
			byte[] by = new byte[1024];
			int len = 0;
			while((len=bi.read(by))!=-1){
			    bs.write(by,0,len);
			}
			bs.close();
			bi.close();
//			File file = new File(fileUrl);
			LOG.info("文件是否存在"+file.exists());
			LOG.info("文件长度"+file.length());
			audoUrl = UploadUtil.amr2Mp3(file,file.getName(), QiNiuSpaceEnum.XIAOQ_MATRIX.getName().toLowerCase(),
					QiNiuSpaceEnum.XIAOQ_MATRIX.getDomain());
			file.delete();
			LOG.info("文件是否存在"+file.exists());
			return audoUrl;
		} catch (Exception e) {
			LOG.error(e.getMessage(),e);
		} 
		return audoUrl;
	}

}
